<template>
  <div class="user-comments">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的评论</span>
      </div>
      
      <div class="empty-block" v-if="commentList.length === 0">
        <el-empty description="暂无评论记录，快去欣赏作品并发表您的见解吧！">
          <el-button type="primary" @click="$router.push('/')">浏览作品</el-button>
        </el-empty>
      </div>
      
      <el-table
        v-else
        :data="commentList"
        style="width: 100%">
        <el-table-column
          label="作品"
          width="120">
          <template slot-scope="{row}">
            <router-link :to="`/detail/${row.photoId}`">
              <el-image 
                style="width: 80px; height: 80px"
                :src="row.photoImgUrl" 
                :preview-src-list="[row.photoImgUrl]">
              </el-image>
            </router-link>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="photoTitle"
          label="作品标题"
          width="150">
          <template slot-scope="{row}">
            <router-link :to="`/detail/${row.photoId}`" class="photo-title">
              {{ row.photoTitle }}
            </router-link>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="content"
          label="评论内容">
          <template slot-scope="{row}">
            <div class="comment-content">{{ row.content }}</div>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="createTime"
          label="评论时间"
          width="180">
          <template slot-scope="{row}">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="状态"
          width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已审核' : '待审核' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="150">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="primary"
              @click="handleViewDetail(row)">查看作品</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteComment(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 编辑评论对话框 -->
    <el-dialog
      title="编辑评论"
      :visible.sync="editDialogVisible"
      width="50%">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="80px">
        <el-form-item label="评论内容" prop="content">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入评论内容"
            v-model="editForm.content">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserComments',
  data() {
    return {
      commentList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      editDialogVisible: false,
      editForm: {
        id: '',
        content: ''
      },
      editRules: {
        content: [
          { required: true, message: '请输入评论内容', trigger: 'blur' },
          { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      },
      submitLoading: false
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.fetchUserComments()
  },
  methods: {
    async fetchUserComments() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          userId: this.userId
        }
        const res = await this.$http.get('/comments/user', { params })
        if (res.data.code === 1) {
          this.commentList = res.data.data.records
          this.total = res.data.data.total
        } else {
          this.$message.error('获取评论记录失败')
        }
      } catch (error) {
        console.error('获取评论记录失败', error)
        this.$message.error('获取评论记录失败')
      } finally {
        this.loading = false
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUserComments()
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    handleViewDetail(row) {
      this.$router.push(`/detail/${row.photoId}`)
    },
    handleEditComment(row) {
      this.editForm.id = row.id
      this.editForm.content = row.content
      this.editDialogVisible = true
    },
    submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            const res = await this.$http.put(`/comments/${this.editForm.id}`, {
              content: this.editForm.content
            })
            if (res.data.code === 1) {
              this.$message.success('修改评论成功')
              this.editDialogVisible = false
              this.fetchUserComments()
            } else {
              this.$message.error(res.data.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改评论失败', error)
            this.$message.error('修改失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    handleDeleteComment(row) {
      this.$confirm('确认删除该评论吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await this.$http.delete(`/comments/${row.id}`)
          if (res.data.code === 1) {
            this.$message.success('删除评论成功')
            this.fetchUserComments()
          } else {
            this.$message.error(res.data.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除评论失败', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.empty-block {
  margin: 40px 0;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.photo-title {
  color: #409EFF;
  text-decoration: none;
}

.photo-title:hover {
  text-decoration: underline;
}

.comment-content {
  max-height: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style> 